package com.fiap.criptografia.simetrica;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * Created with IntelliJ IDEA.
 * User: osvaldoandrade
 * Date: 06/09/12
 * Time: 22:15
 * To change this template use File | Settings | File Templates.
 */
public class Desede {

    private static final String ALG = "DES";

    public static SecretKey criarChaveSecreta() {
        try {
            /* gerador de chave secreta */
            KeyGenerator kg = KeyGenerator.getInstance(ALG);
            SecretKey sk = kg.generateKey();

            System.out.println("Chave gerada = "+ Base64.encode(sk.getEncoded()));

            return sk;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        byte [] plain = "Teste de mensagem criptografada com a minha implementacao de TripleDES...".getBytes("utf-8");

        SecretKey keySpec = criarChaveSecreta();//new SecretKeySpec(keyBytes, "DES");
        SecretKey keySpec2 = criarChaveSecreta();//new SecretKeySpec(key2Bytes, "DES");

        IvParameterSpec iv = new IvParameterSpec(new byte[8]);

        Cipher e1_cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        Cipher e2_cipher = Cipher.getInstance("DES/CBC/NoPadding");

        e1_cipher.init(Cipher.ENCRYPT_MODE, keySpec,iv);
        e2_cipher.init(Cipher.DECRYPT_MODE, keySpec2,iv);

        byte [] cipherText = e1_cipher.doFinal(plain);
        cipherText = e2_cipher.doFinal(cipherText);
        cipherText = e1_cipher.doFinal(cipherText);


        Cipher d1_cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        Cipher d2_cipher = Cipher.getInstance("DES/CBC/NoPadding");

        d1_cipher.init(Cipher.DECRYPT_MODE, keySpec,iv);
        d2_cipher.init(Cipher.ENCRYPT_MODE, keySpec2,iv);


        byte[] output = d1_cipher.doFinal(cipherText);

        output = d2_cipher.doFinal(output);

        output = d1_cipher.doFinal(output);

        System.out.println("Ciphertext: " + new sun.misc.BASE64Encoder().encode(cipherText));


        System.out.println("Output: " + new String(output, "UTF-8"));

    }


}
